package top.aicats.SJCThreadPool;

import org.omg.CORBA.PRIVATE_MEMBER;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author sjc
 * @version 1.0
 * @date 2020/10/1 9:46
 * @email 952491025@qq.com
 */
public class SJCThreadPool {
    private final BlockingQueue<Runnable> taskQueue;
    private WorkThread[] workThreads;
    private static int workNum = 5;
    private static int maxTaskCount = 100;
    private class WorkThread extends Thread {
       @Override
       public void run() {
           Runnable runnable = null;
           try {
               while(!isInterrupted()) {
                   runnable = taskQueue.take();
                   if (runnable != null) {
                       runnable.run();
                   }
                    runnable = null;
               }
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       public void StopWork() {
           interrupt();
       }
    }

    public SJCThreadPool() throws Exception {
        this(workNum, maxTaskCount);
    }
    public SJCThreadPool(int workThreadNum, int maxTaskNum) throws Exception {
        if (workThreadNum < 1) {
            throw new Exception("线程数小于1");
        }
        if (maxTaskNum < 1) {
            throw new Exception("最大任务数小于1");
        }
        this.workNum = workThreadNum;
        this.maxTaskCount = maxTaskNum;
        taskQueue = new ArrayBlockingQueue<Runnable>(maxTaskNum);
        workThreads = new WorkThread[workNum];
        for(int i = 0; i < workNum; i++) {
            workThreads[i] = new WorkThread();
            workThreads[i].start();
        }
    }

    public void execute(Runnable task) {
        try {
            taskQueue.put(task);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    public void destroy() {
        System.out.println("close");
        for (int i = 0; i < workNum; i++) {
            workThreads[i].StopWork();
            workThreads[i] = null;
        }
    }
}
